<?php

/**
 * Class for viewing the JavaScript for a page.
 * The constructor inputs all the page data
 *
 * @author Ian Clarence ian.clarence@gmail.com
 */ 
abstract class ViewJavaScript extends Component {
    
    /**
     * The script is made up solely of an array of code snippets enclosed in a jQuery document ready function.
     * 
     * @var array
     */
    protected $viewCodeSnippets = array();

    /**
     * The constructor.
     *
     * @param array $fields
     */
    public function __construct(array $fields = array()) {        
        parent::__construct($fields);
    }
    
    /**
     * Adding a code snippet to the script.
     * 
     * @param ViewCodeSnippet $viewCodeSnippet
     */
    protected function addCodeSnippet($viewCodeSnippet) {
        if ($viewCodeSnippet instanceof ViewCodeSnippet) {
            $this->viewCodeSnippets[count($this->viewCodeSnippets)] = $viewCodeSnippet;
        }
    }
    
    /**
     * Adding an array of code snippets to the script.
     * 
     * @param array $viewCodeSnippets
     */
    protected function addCodeSnippets($viewCodeSnippets) {
        if (is_array($viewCodeSnippets)) {
            foreach ($viewCodeSnippets as $viewCodeSnippet) {
                $this->addCodeSnippet($viewCodeSnippet);
            }
        }
    }
    
    /**
     * Viewing the whole script.
     * 
     * @return string 
     */
    public function view() {
        $output = 'jQuery(document).ready(function() {' . "\n";
        if (is_array($this->viewCodeSnippets)) {
            foreach ($this->viewCodeSnippets as $viewCodeSnippet) {
                if ($viewCodeSnippet instanceof ViewCodeSnippet) {
                    $output .= $viewCodeSnippet->view() . "\n";
                }
            }
        }
        $output .= '});' . "\n";
        return $output;
    }
    
}